package com.zzl.web;

import com.zzl.entity.User;
import com.zzl.services.UserService;
import com.zzl.services.impl.UserServicesImpl;
import com.zzl.util.DbUtil;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;

public class LoginServlet extends HttpServlet {
    DbUtil dbUtil=new DbUtil();
    UserService userService=new UserServicesImpl();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userName=req.getParameter("userName");
        String password=req.getParameter("password");
        req.setAttribute("userName",userName);
        req.setAttribute("password",password);

        User user=new User();
        user.setUserName(userName);
        user.setPassword(password);

        Connection con=null;
        try {
            con=dbUtil.getCon();
            User currentUser=userService.login(con,user);
            if (currentUser==null){
                req.setAttribute("error","用户名或密码错误");
                req.getRequestDispatcher("index.jsp").forward(req,resp);
            }else {
                HttpSession session=req.getSession();
                session.setAttribute("currentUser",currentUser);
                resp.sendRedirect("main.jsp");
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                dbUtil.closeCon(con);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
